<template>
  <div style="height: 100%;overflow: auto;">
    <div v-show='modifyStatus === "unmodified"'>
      <el-container class='container-add-box'>
        <el-main>
          <el-form ref='formRef' :model='form' :rules='rules' label-width='100px' style='margin-top: 40px'>
            <!-- <el-form-item v-if='showItem("linkWay")' label='连接方式'>
              <el-radio-group v-model='form.linkWay' type="textarea" :rows="6" placeholder='请输入描述'>
                <el-radio :label="0">集群地址</el-radio>
                <el-radio :label="1">Broker地址</el-radio>
              </el-radio-group>
            </el-form-item> -->
            <el-form-item v-if='showItem("groupAddress")' label='集群地址' prop='groupAddress'>
              <el-input v-model='form.groupAddress' type="textarea" :rows="6" :placeholder='getGroupAddressPlaceholder()'></el-input>
            </el-form-item>
            <el-form-item v-if='showItem("BrokerAddress") && form.linkWay === 1' label='Broker地址' prop='BrokerAddress'>
              <el-input v-model='form.BrokerAddress' type="textarea" :rows="6" placeholder='Broker地址，例如IP1:Port,IP2:Port,IP3:Port/子目录'></el-input>
            </el-form-item>

            <el-form-item label='数据源名称' prop='datasourceName'>
              <el-input v-model='form.datasourceName' placeholder='请输入数据源名称'></el-input>
            </el-form-item>
            <el-form-item v-if='showItem("groupName")' label='集群名称'>
              <el-input v-model='form.groupName' placeholder='请输入集群名称'></el-input>
            </el-form-item>
            <el-form-item v-if='showItem("JDBC URL")' label='JDBC URL' prop='url'>
              <el-input v-model='form.url' placeholder='请输入JDBC URL(MongoDB格式为IP:PORT)'></el-input>
            </el-form-item>
            <el-form-item v-if='showItem("authenticationMethod")' label='认证方式' prop='authenticationMethod'>
              <el-select v-model='form.authenticationMethod' placeholder='请选择认证方式'>
                <el-option :value='0' label='SASL_PLAINTEXT'></el-option>
                <el-option :value='1' label='kerberos'></el-option>
                <el-option :value='2' label='无'></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if='showItem("username")'
              label='用户名'
              prop='username'
            >
              <el-input v-model='form.username' placeholder='请输入用户名'></el-input>
            </el-form-item>
            <el-form-item
              v-if='showItem("password")'
              label='密码'
              prop='password'
            >
              <el-input type="password" v-model='form.password' placeholder='请输入密码'></el-input>
            </el-form-item>
            <el-form-item
              v-if='showItem("database")'
              label='数据库'
              prop='database'
            >
              <el-input v-model='form.database' placeholder='请输入数据库'></el-input>
            </el-form-item>

            <!-- <el-form-item label='级别' prop='identifier'>
              <el-radio-group v-model="form.identifier" @change='handleChangeIdentifier'>
                <el-radio :label="1">省</el-radio>
                <el-radio :label="2">市</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if='form.identifier === 2' label='16市' prop='identifier'>
              <el-select v-model="form.cityName" @change='handleChangeCity'>
                <el-option v-for='city in cityListWithoutAll' :label='city.cityName' :value='city.cityName' :key='city'></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item v-if='showItem("datasourceType")' label='数据源类型' prop='identifier'>
              <el-select v-model="form.dataSourceType">
                <el-option v-for='item in datasourceType' :label='item.label' :value='item.value' :key='item'></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label='分类' prop='baseType'>
              <el-radio-group v-model="form.baseType">
                <el-radio v-for='item in dictionaryStore.databaseType' :label='item.value' :key='item'>{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item> -->

            <el-form-item
              v-if='showItem("qualityResultType")'
              label='质控类型'
              prop='qualityResultType'
            >
              <el-input v-model='form.qualityResultType' placeholder='请输入质控类型'></el-input>
            </el-form-item>
            <el-form-item label="数据权限">
              <el-radio-group v-model="form.openLevel">
                <el-radio label="1">私人</el-radio>
                <el-radio label="2">本角色</el-radio>
                <el-radio label="3">公开</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-main>
      </el-container>
      <div style='text-align: center; padding: 10px; border-top: 0'>
        <el-button type='primary' @click='handleOk' :loading='addLoading'>确定</el-button>
      </div>
    </div>
    <div v-show='modifyStatus === "modified"'>
      <el-result
        icon="success"
        title="修改成功"
      >
      </el-result>
    </div>
  </div>
</template>

<script setup>
import { remoteUpdate, remoteTest } from '@/api/datasourceCenter'
import { ElMessage } from 'element-plus'
import _cloneDeep from 'lodash/cloneDeep'
// import {cityListWithoutAll} from '@/utils/city.js'
// import { useDictionaryStore } from '@/store/modules/dictionary'
import { sm4Encrypt, sm4Decrypt } from '@/utils/sm4'

// const dictionaryStore = useDictionaryStore()


const props = defineProps({
  datasource: {
    type: Object,
    default: {},
    required: true,
  },
  modifyKey: {
    type: String,
    default: '',
    required: true,
  }
})
const emits = defineEmits(['refresh'])
const formRef = ref()
const form = ref({
  username: '',
  password: '',
  type: '',
  datasourceName: '',
  description: '',
  url: '',
  groupAddress: '',
  BrokerAddress: '',
  database: '',
  groupName: '',
  linkWay: 0,
  authenticationMethod: 2,
  identifier: 1,
  baseType: 3,
  cityName: '济南市',
  qualityResultType: '',
  openLevel: '1'
})
const rules = {
  type: [{required: true, message: '请填写数据源类型', trigger: 'blur'}],
  datasourceName: [{required: true, message: '请填写数据源名称', trigger: 'blur'}],
  url: [{required: true, message: '请填写JDBC URL', trigger: 'blur'}],
  groupAddress: [{required: true, message: '请填写集群地址', trigger: 'blur'}],
  database: [{required: true, message: '请填写数据库', trigger: 'blur'}],
  linkWay: [{required: true, message: '请选择连接方式', trigger: 'trigger'}],
  password: [{required: true, message: '请填写密码', trigger: 'blur'}],
  username: [{required: true, message: '请填写用户名', trigger: 'blur'}],
}

// dictionaryStore.getDatabaseType()


const showItem = function(itemName) {
  switch (form.value.type.toLowerCase()) {
    case 'oracle':
    case 'sqlserver':
    case 'mysql':
    case 'duckdb':
    case 'postgresql':
    case 'starrocks':
    case 'doris':

      return ['JDBC URL', 'username', 'password'].includes(itemName)
      break;
    case 'elasticsearch':
      return ['groupAddress','username', 'password','groupName'].includes(itemName)
      break;
    case 'mongodb':
      return ['JDBC URL', 'username', 'password', 'database'].includes(itemName)
      break;
    case 'kafka':
      return ['groupAddress',  'username', 'password'].includes(itemName)
      break;
    case 'clickhouse':
      return  ['JDBC URL', 'username', 'password', 'qualityResultType'].includes(itemName)
      break;
    default: return true; break;
  }
}
// 设置不同数据库类型此选项placeholder
const getGroupAddressPlaceholder = () => {
  if (form.value.type.toLowerCase() === 'kafka') {
    return '集群地址，单个节点地址采用host:port形式，多个节点的地址用逗号连接'
  }
  if (form.value.type.toLowerCase() === 'mongodb') {
    return 'MongoDB集群地址，例如：IP1:Port,IP2:Port,IP3:Port'
  }
}
const modifyStatus = ref('unmodified') // 未修改unmodified 修改成功modified
const addLoading = ref(false) // 添加btn loading
const handleOk = function() { // 添加
  formRef.value.validate().then(() => {
    addLoading.value = true
    const temp = _cloneDeep(form.value)
    if (['elasticsearch'].includes(form.value.type.toLowerCase()) && !Array.isArray(temp.groupAddress)) {
      temp.groupAddress = temp.groupAddress.split(',')
    }

    //加密密码
    let params={
      ...temp,
      password: sm4Encrypt(temp.password)
    }

    remoteUpdate(params).then(res => {
      ElMessage.success(res.msg)
      modifyStatus.value = 'modified'
      emits('refresh')
    }).finally(() => {
      addLoading.value = false
    })
  }).catch((e) => {
    ElMessage.error('请填写必填项')
    addLoading.value = false
  })
}
watch(() => props.datasource, () => {
  console.log(111);
  Object.assign(form.value, props.datasource[props.modifyKey])
  form.value.password = sm4Decrypt(form.value.password)

}, {
  deep: true,
  immediate: true,
})
watch(() => props.modifyKey, () => {
  console.log(111);
  Object.assign(form.value, props.datasource[props.modifyKey])
  //解密密码
  form.value.password = sm4Decrypt(form.value.password)
}, {
  deep: true,
  immediate: true,
})
// watch(() => form.value.identifier, (val) => {
//   if (val === 1) {
//     form.value.cityName = '山东省'
//     form.value.cityCode = '370000'
//   }
//   if (val === 2) {
//     form.value.cityName = '济南市'
//     form.value.cityCode = '370100'
//   }
// }, {
//   immediate: true,
// })
</script>

<style lang='scss' scoped>
@import "../style/addDatasource.scss";
</style>
